/**
 * Created by hqh on 2016/8/17.
 */
var loadBool = true, //列表数据请求是否完成标识
        perPage = 15;       //列表每页显示条数

//页面初始化
$(function () {
    showUsersList();

    //新增用户 弹框
    $('#add').click(function () {
        var content =
                '<div class="add-user-wrapper">' +
                '<div class="form-inline">' +
                '<div class="form-group">' +
                '<label class="form-label-sm" for="phone">电话:</label>' +
                '<input class="form-control" type="text" id="phone" val="" />' +
                '<i class="mandatory" id="phoneMark"></i>' +
                '</div>' +
                '</div>' +
                '<div class="form-inline">' +
                '<div class="form-group">' +
                '<label class="form-label-sm" for="password">密码:</label>' +
                '<input class="form-control" type="password" id="password" val="" />' +
                '<i class="mandatory" id="passwordMark"></i>' +
                '</div>' +
                '</div>' +
                '<div class="form-inline">' +
                '<div class="form-group">' +
                '<label class="form-label-sm" for="nickname">昵称:</label>' +
                '<input class="form-control" type="text" id="nickname" value=""/>' +
                '<i class="mandatory" id="nicknameMark"></i>' +
                '</div>' +
                '</div>' +
                '<div class="form-inline">' +
                '<div class="form-group">' +
                '<label class="form-label-sm" for="role">角色:</label>' +
                '<select class="form-control" name="role" id="role">' +
                // '<option value="管理员">管理员</option>' +
                '</select>' +
                '<i class="mandatory" id="roleMark"></i>' +
                '</div>' +
                '</div>' +
                '<div class="bot-button bot-two-button">' +
                '<input id="confirm" class="btn btn-lg-blue" type="button" value="提交">' +
                '<input id="cancel" class="btn btn-lg-blue" type="button" value="取消">' +
                '</div>' +
                '</div>';
        layer.open({
            type: 1,
            skin: 'layui-layer-rim',
            area: ['320px,auto'],
            title: '新增用户',
            closeBtn: 0,
            content: content,
            success: function (layero, index) {
                getRoles(layero, index, "*");
                addUser(layero, index);
            }
        });
    });

    //删除用户 按钮
    $('#delete').click(function () {
        var $target = $('#usersList tr input[type="checkbox"]:checked').parents('tr');
        if ($target.length == 0) {
            bbx_alert_error('请先选择要删除的用户！');
        } else {
            var usersArr = [];
            $target.each(function () {
                var delPhone = $(this).find('td').eq(3).text();
                usersArr.push(delPhone);
            });
            console.log('删除的用户组：' + usersArr);
            delUsers(usersArr);
        }
    });

    //修改用户 按钮
    $('#usersList').delegate('.modify', 'click', function () {
        var phone = $(this).parents('tr').find('td').eq(3).text();
        var content =
                '<div class="add-user-wrapper">' +
                '<div class="form-inline">' +
                '<div class="form-group">' +
                '<label class="form-label" for="username">注册电话:</label>' +
                '<span class="form-text-lg" id="phone"></span>' +
                '<i class="mandatory" id="phoneMark"></i>' +
                '</div>' +
                '</div>' +
                '<div class="form-inline">' +
                '<div class="form-group">' +
                '<label class="form-label" for="nickname">昵称:</label>' +
                '<input class="form-control" type="text" id="nickname" value="" />' +
                '<i class="mandatory" id="nicknameMark"></i>' +
                '</div>' +
                '</div>' +
                '<div class="form-inline">' +
                '<div class="form-group">' +
                '<label class="form-label" for="role">角色:</label>' +
                '<select class="form-control" name="role" id="role">' +
                // '<option value="管理员">管理员</option>' +
                '</select>' +
                '<i class="mandatory" id="rolenameMark"></i>' +
                '</div>' +
                '</div>' +
                '<div class="form-inline">' +
                '<div class="form-group">' +
                '<label class="form-label">是否修改密码:</label>' +
                '<label for="change" class="radio-label"><input type="radio" id="change" name="changePwd" value="1">是</label>' +
                '<label for="nochange" class="radio-label"><input type="radio" id="nochange" name="changePwd" checked="checked" value="0">否</label>' +
                '</div>' +
                '</div>' +
                '<div class="password-wrapper" style="display: none">' +
                '<div class="form-inline">' +
                '<div class="form-group">' +
                '<label class="form-label" for="oldPwd">旧密码:</label>' +
                '<input class="form-control" type="password" id="oldPwd" />' +
                '<i class="mandatory" id="oldPwdMark"></i>' +
                '</div>' +
                '</div>' +
                '<div class="form-inline">' +
                '<div class="form-group">' +
                '<label class="form-label" for="newPwd">新密码:</label>' +
                '<input class="form-control" type="password" id="newPwd" />' +
                '<i class="mandatory" id="newPwdMark"></i>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="bot-button bot-two-button">' +
                '<input id="confirm" class="btn btn-lg-blue" type="button" value="提交">' +
                '<input id="cancel" class="btn btn-lg-blue" type="button" value="取消">' +
                '</div>' +
                '</div>' +
                '</div>';
        layer.open({
            type: 1,
            skin: 'layui-layer-rim',
            area:['660px','450px'],
            title: '修改用户',
            closeBtn: 0,
            content: content,
            success: function (layero, index) {
                getRoles(layero, index, phone);
                // getUserInfo(layero, index, phone);
                isChangePwd(layero, index);
                modifyUser(layero, index);
            }
        });
        return false;
    });
});

//显示用户列表 从第1条记录开始
function showUsersList() {
    $("#curPage").text(1);
    $("#pages").text(1);
    getCurPage(1);
}

//获取当前活动页的用户列表数据
function getCurPage(curPage) {
    if (!loadBool) {
        return;
    } else {
        loadBool = false;
        $('#usersList').empty();
        var loadingIndex = layer.load(2, {
            shade: [0.1, '#fff']    //0.1透明度的白色背景
        });
        var data = JSON.stringify({
            'phone': '',
            'username': '',
            'pos': (curPage - 1) * perPage,
            'limit': perPage
        });
        console.log('data');
        $.ajax({
            type: "POST",
            url: "/user/query",
            data: data,
            dataType: "json",
            success: function (res) {
                console.log(res);
                layer.close(loadingIndex);
                if (res.status == 0) {
                    console.log('获取用户列表：' + JSON.stringify(res));
                    var pageNum = Math.ceil(res.data.count / perPage);
                    $("#pages").text(pageNum);
                    $('#curPage').text(curPage);
                    for (var i = 0, list = res.data.data; i < list.length; i++) {
                        for (var key in list[i]) {
                            if (list[i][key] == undefined || list[i][key] == null) {
                                list[i][key] = " ";
                            }
                        }
                        var item =
                                '<tr>' +
                                '<td><input type="checkbox" /></td>' +
                                '<td style="display: none;">' + list[i].id + '</td>' +
                                '<td style="display: none">' + list[i].uid + '</td>' +
                                '<td>' + list[i].phone + '</td>' +
                                '<td>' + list[i].username + '</td>' +
                                '<td style="display: none">' + list[i].role + '</td>' +
                                '<td>' + list[i].role_name + '</td>' +
                                '<td>' + list[i].create_time + '</td>' +
                                '<td>' +
                                '<a class="modify" href="javascript:void(0);" title="">修改</a>' +
                                '</td>' +
                                '</tr>';
                        $('#usersList').append(item);
                    }
                } else {
                    bbx_alert_error(res.message);
                }
                loadBool = true;
            },
            error: function (xhr, status, error) {
                layer.close(loadingIndex);
                bbx_alert_error('出错啦~');
                loadBool = true;
            }
        });
    }
}

//新增用户
function addUser(layero, index) {
    layero.find('#phone').on('keyup', function () {
        onlyNumber2(this);
    });
    layero.find('#phone').on('input', function () {
        onlyNumber2(this);
    });
    //清空表单信息
    layero.find('#phone,#password,#nickname').val('');
    layero.find('#confirm').click(function () {
        if (checkUserInfo(layero, index)) {
            var data = JSON.stringify({
                'username': layero.find('#nickname').val(),
                'password': hex_md5(layero.find('#password').val()), //通过md5加密的字符串
                'phone': layero.find('#phone').val(),
                'role': String(layero.find('#role option:selected').attr('code')),
                'role_name': layero.find('#role option:selected').val()
            });
            console.log('新增用户传参：' + data);
            $.ajax({
                type: "POST",
                url: "/user/auser",
                data: data,
                dataType: "json",
                success: function (res) {
                    console.log(res);
                    if (res.status == 0) {
                        layer.msg('添加成功！', {icon: 1, time: 1000}, function () {
                            layer.close(index);
                            showUsersList();
                        });
                    } else if (res.status == -1) {
                        bbx_alert_error('用户已存在！');
                    } else {
                        bbx_alert_error('添加失败！');
                    }
                },
                error: function (xhr, status, error) {
                    console.log(error);
                    bbx_alert_error('出错啦~');
                }
            });
        } else {
            // do nothing
        }
    });

    layero.find('#cancel').click(function () {
        layer.close(index);
    });
}

//限制只能输入数字
function onlyNumber2(obj) {
    obj.value = obj.value.replace(/[^\d]/g, "");       //先把非数字的都替换掉，除了数字
}

//新增用户时 检查用户信息输入
function checkUserInfo(layero, index) {
    var phone = layero.find('#phone').val(),
            password = layero.find('#password').val(),
            nickname = layero.find('#nickname').val();
    if (phone == '') {
        $('#phoneMark').text('电话不能为空');
        return false;
    } else {
        $('#phoneMark').text('');
    }
    if (password == '') {
        $('#passwordMark').text('密码不能为空');
        return false;
    } else {
        $('#passwordMark').text('');
    }
    if (nickname == '') {
        $('#nicknameMark').text('昵称不能为空');
        return false;
    } else {
        $('#nicknameMark').text('');
    }
    return true;
}

//修改用户时 检查用户信息输入
function checkUserInfo2(layero, index) {
    var nickname = layero.find('#nickname').val(),
            newpassword = layero.find('#newPwd').val();
    if (nickname == '') {
        $('#nicknameMark').text('昵称不能为空');
        return false;
    } else {
        $('#nicknameMark').text('');
    }
    if (Number(layero.find('input[name="changePwd"]:checked').val()) == 1) {//修改密码
        if (newpassword == '') {
            $('#newPwdMark').text('密码不能为空');
            return false;
        }
    }
    $('#newPwdMark').text('');
//    if (newpassword == '') {
//        $('#newPwdMark').text('密码不能为空');
//        return false;
//    } else {
//        $('#newPwdMark').text('');
//    }
    return true;
}

//批量删除用户
function delUsers(usersArr) {
    var data = JSON.stringify({
        'phones': usersArr
    });
    console.log('删除用户传参：' + data);
    $.ajax({
        type: "POST",
        url: "/user/del",
        data: data,
        dataType: "json",
        success: function (res) {
            console.log(res);
            if (res.status == 0) {
                layer.msg('删除成功！', {icon: 1, time: 1000}, function () {
                    showUsersList();
                });
            } else {
                bbx_alert_error('删除失败！');
            }
        },
        error: function (xhr, status, error) {
            console.log(error);
            bbx_alert_error('出错啦~');
        }
    });
}

//修改用户
function modifyUser(layero, index) {
    layero.find('#confirm').click(function () {
        if (checkUserInfo2(layero, index)) {
            var data = JSON.stringify({
                'username': layero.find('#nickname').val(),
                'phone': layero.find('#phone').text(),
                'role': String(layero.find('#role option:selected').attr('code')),
                'role_name': layero.find('#role option:selected').val(),
                'setpwd': Number(layero.find('input[name="changePwd"]:checked').val()), //1:修改密码，0:不修改密码
                'oldpwd': hex_md5($('#oldPwd').val()), //通过md5加密的字符串
                'newpwd': hex_md5($('#newPwd').val())                               //通过md5加密的字符串
            });
            console.log('修改用户信息传参：' + data);
            $.ajax({
                type: "POST",
                url: "/user/modify",

                data: data,
                dataType: "json",
                success: function (res) {
                    console.log(res);
                    if (res.status == 0) {
                        layer.msg('修改成功！', {icon: 1, time: 1000}, function () {
                            layer.close(index);
                            showUsersList();
                        });
                    } else if (res.status == -3) {
                        layero.find('#oldPwdMark').text('密码错误，请重新输入！');
                    } else {
                        bbx_alert_error('修改失败！');
                    }
                },
                error: function (xhr, status, error) {
                    console.log(error);
                    bbx_alert_error('出错啦~');
                }
            });
        } else {
            //do nothing
        }
    });

    layero.find('#cancel').click(function () {
        layer.close(index);
    });
}

//获取用户信息
function getUserInfo(layero, index, phone) {
    var data = JSON.stringify({
        'phone': phone
    });
    $.ajax({
        type: 'POST',
        url: '/user/ginfo',
        data: data,
        dataType: 'json',
        success: function (res) {
            console.log('获取该用户信息：' + JSON.stringify(res));
            if (res.status == 0) {
                layero.find('#phone').text(phone);
                layero.find('#nickname').val(res.message.username);
                layero.find('#role').val(res.message.role_name);
                layero.find('#role option[text="' + res.message.role_name + '"]').prop('selected',true);
            } else {
                bbx_alert_error('获取用户信息失败！');
            }
        },
        error: function (xhr, status, error) {
            console.log(error);
            bbx_alert_error('出错啦~');
        }
    });
}

//获取角色
function getRoles(layero, index, phone) {
    var data = JSON.stringify({
        'name': '',
        'type': '',
        'pos': 0,
        'limit': 9999999999
    });
    console.log('查询角色传参：' + data);
    $.ajax({
        type: "POST",
        url: "/role/query",
        data: data,
        dataType: "json",
        success: function (res) {
            console.log('获取所有角色：' + JSON.stringify(res));
            if (res.status == 0) {
                layero.find('#role').empty();
                //把所有角色填充到下拉选框中供用户选择
                var count = res.data.count,
                    list = res.data.data;
                for (var i = 0; i < count; i++) {
                    var item = '<option text="' + list[i].name + '" code="' + list[i].role+ '">' + list[i].name + '</option>';
                    layero.find('#role').append(item);
                }
                if(phone=='*'){
                    //新增用户
                }
                else{
                    //修改用户
                    getUserInfo(layero,index,phone);
                }
            }
            else {
                bbx_alert_error('获取角色失败！');
            }
        },
        error: function (xhr, status, error) {
            bbx_alert_error('出错啦~');
        }
    });
}

//选择是否修改密码
function isChangePwd(layero, index) {
    layero.find('input[name="changePwd"]').click(function () {
        var value = layero.find('input[name="changePwd"]:checked').val();
        console.log('选中：' + value);
        switch (value) {
            case '1':
                layero.find('.password-wrapper').show();
                break;
            case '0':
                layero.find('.password-wrapper').hide();
        }
    });
}

$(document).ready(function () {
    //显示上一页
    $('#lastPage').click(function () {
        var curPage = parseInt($("#curPage").text());
        if (curPage <= 1) {
            return;
        } else {
            getCurPage(curPage - 1);
        }
    });

    //显示下一页
    $('#nextPage').click(function () {
        var curPage = parseInt($("#curPage").text()),
                totalpage = parseInt($('#pages').text());
        if (curPage == totalpage) {
            return;
        } else {
            getCurPage(curPage + 1);
        }
    });
});

$(document).ready(function () {
    // 全选反选, 选择
    $('table thead,#checkAll').click(function () {
        checkAll('#checkAll');
    });
    $('#usersList').delegate('tr', 'click', function () {
        var target = $(this).find('input[type="checkbox"]').get();
        checkItem(target);
    });
    $('#usersList').delegate('input[type="checkbox"]', 'click', function () {
        checkItem(this);
    });

    function checkAll(target) {
        if ($(target).prop('checked')) {
            $(target).prop('checked', false);
            $('#usersList tr input[type="checkbox"]').prop('checked', false);
        } else {
            $(target).prop('checked', true);
            $('#usersList tr input[type="checkbox"]').prop('checked', true);
        }
    }
    function checkItem(target) {
        if ($(target).prop('checked')) {
            $(target).prop('checked', false);
            $('#checkAll').prop('checked', false);
        } else {
            $(target).prop('checked', true);
        }
    }
}
);
